<?php
/* 登录 */
namespace Api\Controller;
use Think\Controller;
use Think\Log;
class PLoginController extends Controller {

 	protected $accountArr = array(62179101,62179201,62139001,62179301,62179501,
								  62179601,62252101,62252201,62135101,62135201,
								  62252301,62251601,62251801,62251701,62251901,
								  62252001,62252301,98430301,98430101);//,8430101);
 	
	public function __construct()
	{
		//解决跨域
		echoHeader();
	}

	//生成验证码
	public function code()
	{	
		$phone = I('post.phone', '', 'trim');
		if(!is_numeric($phone) or mb_strlen($phone) != 11 or substr($phone, 0, 1) != 1){
			return $this->ajaxReturn(array('err_code'=>10001, 'err_msg'=>'手机号码错误'));
		}

		$model = D("PUser");
		$result = $model->send($phone);
		if(isset($result['code']) and $result['code'] == 200){
			return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>"短信发送成功"));
		}else{
			Log::write(var_export($result,true),'result');
			return $this->ajaxReturn(array('err_code'=>20001, 'err_msg'=>"短信发送失败"));
		}

	}


	
	public function register()
	{
		$phone = I('post.phone', '', 'trim');
		$password = I('post.password', '', 'trim');
		$name = I('post.name', '', 'trim');
		$account = I('post.account', '', 'trim');
		$code = I('post.code', 0, 'trim');
		$model = D("PUser");

		if(empty($phone)){
			return $this->ajaxReturn(array('err_code'=>10002,'err_msg'=>'手机号码错误'));
		}

		$verify = $model->verify($phone, $code);

		if (!isset($verify['code']) or $verify['code'] != 200) {
			return $this->ajaxReturn(array('err_code'=>10003,'err_msg'=>'验证码错误'));
		}
		$actId = I('post.act_id', 0, 'intval');
		if (empty($name)) {
			return $this->ajaxReturn(array('err_code'=>10005,'err_msg'=>'请输入姓名'));
		}
		//验证卡号长度与前缀
		$len = strlen($account);
		if ($len != 15 and $len != 16) {
			$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的卡号！'));
		}
		$seven = substr($account, 0, 7);
		$eight = substr($account, 0, 8);
		if (!in_array($eight, $this->accountArr) and $seven != 8430101) {
			$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的卡号！'));
		}

		if(!preg_match("/[\w\W]{6,16}/", $password)){
			return $this->ajaxReturn(array('err_code'=>10007,'err_msg'=>'密码格式不对'));
		}
		
		$map['phone'] = $phone;
		$map['is_deleted'] = 0;
		$user = M("PUser")->where($map)->find();
		if($user){
			$this->ajaxReturn(array('err_code'=>20001,'err_msg'=>'手机号码已注册'));
		}

		$map['salt'] = rand(1, 999999);
		$map['password'] = md5($password.$map['salt']);
		$map['name'] = $name;
		$map['account'] = $account;
		$map['add_time'] = time();
		$map['lottery_time'] = 0;
		$res = M("PUser")->add($map);
		if (!$res) {
			return $this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'注册失败！'));
		}

		unset($map['salt']);
		unset($map['password']);
        $map['score']=user_score_sum($res);
		session('p_user', $map);
		if ($actId) {
			$actMap['is_deleted'] = 0;
			$actMap['status'] = 1;
			$actMap['id'] = $actId;
			$act = M("PActivity")->where($actMap)->find();
			if($act){
				M()->startTrans();
				$addScore = M("PUser")->where('id='.$res)->setInc('score', $act['enroll_score']);
				if($addScore){

                    $expire=M('PConfig')->where('key','=','sign_expire')->find();

                    $record['user_id'] = $res;
					$record['act_id'] = $actId;
					$record['add_time'] = time();
					$record['type'] = 1;
					$record['score'] = $act['enroll_score'];
                    $record['consume'] = $act['enroll_score'];
                    $record['expire_time']=time()+$expire['value']*3600*24;
					$rec = M("PScoreRecord")->add($record);
					if($rec){
                        consume_score($res,$act['enroll_score']);

                        M()->commit();
					}else{
						M()->rollback();
					}
				}else{
					M()->rollback();
				}
			}
		}
		return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>'注册成功！', 'data'=>$res));

	}

	public function login()
	{
		$phone = I('post.phone', '', 'trim');
		$password = I('post.password', '', 'trim');

		$map['phone'] = $phone;
		$map['is_deleted'] = 0;

		$user = M('PUser')->where($map)->find();
		if (!$user) {
			return $this->ajaxReturn(array('err_code'=>20001, 'err_msg'=>'用户不存在！'));
		}
		if ($user['password'] != md5($password.$user['salt'])) {
			return $this->ajaxReturn(array('err_code'=>20002, 'err_msg'=>'账号或密码错误！'));
		}
		$start = date("Y-m-d", $user['add_time']);
		$end = date("Y-m-d", strtotime("-31 days"));
		$start = strtotime($start);
		$end = strtotime($end);
		if($end > $start) {
            $data['isShowBenginnerWelfare'] = true;//false;
			$dayLag = ceil(($end - $start)/(3600*24)) + 31;
		}else {
			$data['isShowBenginnerWelfare'] = true;
			$dayLag = ceil(($start - $end)/(3600*24));
		}
		unset($user['salt']);
		unset($user['password']);
        $user['score']=user_score_sum($user['id']);
        session('p_user', $user);
		$data['userId'] = $user['id'];
        $data['address']=$user['address'];
		$data['dayLag'] = $dayLag;

        unset($map);

		return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>'登录成功','data'=>$data));
	}

	public function reset()
	{
		$model = D("PUser");

		$password = I('post.password', '', 'trim');
		if(!preg_match("/[\w\W]{6,16}/", $password)){
			return $this->ajaxReturn(array('err_code'=>10001,'err_msg'=>'密码格式不对'));
		}
		$confirmPass = I('post.confirm_password', '', 'trim');
		if ($password != $confirmPass) {
			return $this->ajaxReturn(array('err_code'=>10003,'err_msg'=>'新密码与确认密码不一致'));
		}
		$phone = I('post.phone', '', 'trim');
		$map['phone'] = $phone;
		$map['is_deleted'] = 0;
		$user = $model->where($map)->find();
		if(!$user){
			return $this->ajaxReturn(array('err_code'=>20001, 'err_msg'=>'用户不存在！'));
		}

		$code = I('post.code', '', 'trim');

		$verify = $model->verify($phone, $code);
		if (!isset($verify['code']) or $verify['code'] != 200) {
			return $this->ajaxReturn(array('err_code'=>10002,'err_msg'=>'验证码错误'));
		}

		$salt = rand(1,999999);
		$data['password'] = md5($password.$salt);
		$data['salt'] = $salt;
		$res = $model->where($map)->save($data);
		if ($res !== false) {
			return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>"重置密码成功"));
		}else{
			return $this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'重置密码失败！'));
		}
		
	}

	public function change(){
		$user = session('p_user');
		if(!$user){
			return $this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请登录！'));
		}
		$oldPass = I('post.old_password', '', 'trim');
		$newPass = I('post.password', '', 'trim');
		$confirm = I('post.confirm', '', 'trim');

		if(!preg_match("/[\w\W]{6,16}/", $newPass)){
			return $this->ajaxReturn(array('err_code'=>10001,'err_msg'=>'新密码格式不对'));
		}
		if($newPass != $confirm){
			return $this->ajaxReturn(array('err_code'=>10002,'err_msg'=>'新密码与确认密码不一致'));
		}
		if ($oldPass == $newPass) {
			return $this->ajaxReturn(array('err_code'=>10003,'err_msg'=>'新密码与旧密码一致'));			
		}
		$map['phone'] = $user['phone'];
		$map['is_deleted'] = 0;
		$userinfo = M("PUser")->where($map)->find();
		if(!$userinfo){
			return $this->ajaxReturn(array('err_code'=>20001, 'err_msg'=>'用户不存在！'));
		}
		if($userinfo['password'] != md5($oldPass.$userinfo['salt'])){
			return $this->ajaxReturn(array('err_code'=>10004, 'err_msg'=>'密码错误！'));
		}

		$data['password'] = md5($newPass.$userinfo['salt']);
		$res = M("PUser")->where($map)->save($data);
		if ($res !== false) {
			return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>'修改密码成功'));
		}else{
			return $this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'修改密码失败！'));
		}
	}

	public function userCenter()
	{
		$user = session('p_user');
		if(!$user){
			return $this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请登录！'));
		}
		
		$userInfo = M("PUser")->field('id,name,lottery_time,account,phone')->where(array('phone'=>$user['phone'],'is_deleted'=>0))->find();
		if(!$userInfo){
			return $this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请登录！'));
		}

		$map['is_deleted'] = 0;
		$map['status'] = 1;
		$act = M("PActivity")->where($map)->field('id,name,url,description')
			->order('id desc')->find();
		if ($act) {
			$act['description'] = htmlspecialchars_decode($act['description']);
		}else{
			$act = array();
		}
        $userInfo['score']=user_score_sum($user['id']);
		return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$userInfo, 'data'=>$act));
	}

	public function loadConfig(){
			$phone = I('post.phone', '', 'trim');

          $list = M("PConfig")->select();
		return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$list));


    }

	public function updateUserCenter(){
	    $user = session('p_user');
        if(!$user){
        	return $this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请登录！'));
        }
/*
        //验证卡号长度与前缀
		$len = strlen(I('post.account', '', 'trim'));
		if ($len != 15 and $len != 16) {
			$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的验证码！'));
		}
		$seven = substr(I('post.account', '', 'trim'), 0, 7);
		$eight = substr(I('post.account', '', 'trim'), 0, 8);
		if (!in_array($eight, $this->accountArr) and $seven != 8430101) {
			$this->ajaxReturn(array('err_code'=>10006,'err_msg'=>'请输入正确的验证码！'));
		}


        if(empty(I('post.phone', '', 'trim'))){
             $this->ajaxReturn(array('err_code'=>20001,'err_msg'=>'手机号码不能为空'));
        }
*/
        if(empty(I('post.name', '', 'trim'))){
             $this->ajaxReturn(array('err_code'=>20001,'err_msg'=>'用户名不能为空'));
        }
/*
        $code = I('post.code', 0, 'trim');
        if(empty($code)){
             $this->ajaxReturn(array('err_code'=>20001,'err_msg'=>'验证码不能为空'));
        }

		$verify = D("PUser")->verify(I('post.phone', '', 'trim'), $code);

		if (!isset($verify['code']) or $verify['code'] != 200) {
			return $this->ajaxReturn(array('err_code'=>10003,'err_msg'=>'验证码错误'));
		}
*/
        if(empty(I('post.account', '', 'trim'))){
             $this->ajaxReturn(array('err_code'=>20001,'err_msg'=>'银行卡号不能为空'));
        }


        $user_id=$user['id'];
        $map['phone'] = I('post.phone', '', 'trim');
        $user = M("PUser")->where($map)->find();
        if($user && $user['id']!=$user_id){
        	$this->ajaxReturn(array('err_code'=>20001,'err_msg'=>'手机号码已注册'));
        }

        unset($map);
        $map['account'] = I('post.account', '', 'trim');
        $user = M("PUser")->where($map)->find();
        if($user && $user['id']!=$user_id){
        	$this->ajaxReturn(array('err_code'=>20001,'err_msg'=>'银行卡号已注册'));
        }

        unset($map);

        $map['id'] = $user_id;
        $data['phone'] = I('post.phone', '', 'trim');
        $data['name'] = I('post.name', '', 'trim');
        $data['account'] = I('post.account', '', 'trim');
        $data['address'] = I('post.address', '', 'trim');

        $res = M("PUser")->where($map)->save($data);
        if ($res !== false) {
        	return $this->ajaxReturn(array('err_code'=>200, 'err_msg'=>'修改帐号信息成功'));
        }else{
        	return $this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'修改信息失败！'));
        }
      }

      public function checkAndRoll()
      {
         $where['is_deleted']=0;
		$total = M("PUser")->where($map)->count();
		$pageIndex = I('get.page', 1, 'intval');
		$page = $this->pagination($total, 100 ,$pageIndex);

         $list = M("PUser")->field('id,name,score')->where($where)->limit($page['offset'], $page['limit'])->select();

		 foreach ($list as $k => $v) {
		    //7月前的积分总量
            $data=M("PScoreRecord")->query("select sum(score) as score from zsf_p_score_record where is_deleted=0 and  user_id = ".$v['id']." and add_time<1498838400");
            $last_totle=$data[0]['score'];
            //7月份的积分消耗量
            $data=M("PScoreRecord")->query("select sum(score) as score from zsf_p_score_record where is_deleted=0 and score<0 and  user_id = ".$v['id']." and add_time>=1498838400 && add_time<=1501516799");
            $last_seven_totle=$data[0]['score'];

            //7月份的积分新增量
            $data=M("PScoreRecord")->query("select sum(score) as score from zsf_p_score_record where is_deleted=0 and score>0 and  user_id = ".$v['id']." and add_time>=1498838400 && add_time<=1501516799");
		    $new_seven_totle=$data[0]['score'];

		    $new_totale=($last_totle-$last_seven_totle);
		    if($new_totale>0)
		        $new_totale=$new_seven_totle+$new_totale;
		    else
		        $new_totale=$new_seven_totle;
		    if($new_totale<1)
		        $new_totale=0;

            echo '用户ID：'.$v['id'].' 用户名：'.$v['name'].' 用户现有积分：'.$v['score'].' 用户7月后新的记录总量积分：'.$new_totale.'<br />';
         }

      }

      public function resetScore()
      {
        $where['is_deleted']=0;
        $where['score']=array('gt','20');

		$total = M("PUser")->where($map)->count();
		$pageIndex = I('get.page', 1, 'intval');
		$page = $this->pagination($total, 300 ,$pageIndex);

		$model=M("PUser");

         $list = $model->field('id,name,score')->where($where)->limit($page['offset'], $page['limit'])->select();

         if(count($list)>0)
    		 $records=M("PScoreRecord")->query("select score,add_time,user_id from zsf_p_score_record where is_deleted=0");

         else
            $records=array();

         $model->startTrans();
		 foreach ($list as $k => $v) {
		    //7月前的积分总量

		    $last_totle=0;
		    $last_seven_totle=0;//7月份的积分消耗量
		    $new_seven_totle=0;//7月份的积分新增量
		    foreach($records as $p => $p2){
    		    if($records['user_id']==$v['id']){
    		    if($p2['add_time']<1498838400){
                		            $last_totle+=$p2['score'];
                		        }
                		        else if($p2['add_time']>=1498838400 && $p2['add_time']<=1501516799){
                		            if($p2['score']<0)
                    		            $last_seven_totle+=$p2['score'];
                    		        else
                    		            $new_seven_totle+=$p2['score'];
                		        }

	    	    }

		    }


		    if($last_seven_totle==0){
		                	$new_totale=$new_seven_totle;

		    }

		    else {
		        $new_totale=($last_totle+$last_seven_totle);
            	if($new_totale<0)
            	     $new_totale=$new_seven_totle+$new_totale;
            	else
            	     $new_totale=$new_seven_totle;
		    }



		    if($new_totale<1)
		        $new_totale=0;


		    $where['id']=$v['id'];
		    $data=$model->where($where)->find();
		    $data['score']=$new_totale;
		    $model->where($where)->save($data);

         }
         $model->commit();


      }

      private function pagination($total, $pageSize, $pageIndex)
      	{
      	    $page = array();
      	    $totalPages = ceil($total / $pageSize);
      	    $pageIndex <= 0 and $pageIndex = 1;
      	    $offset = ($pageIndex - 1) * $pageSize;

      	    $page['limit'] = $pageSize;
      	    $page['offset'] = $offset;
      	    $page['total'] = (int)$total;//总条目数
      	    $page['total_pages'] = (int)$totalPages;//总页数
      	    $page['current_page'] = $pageIndex;//当前页数
      	    $page['has_nextpage'] = $totalPages > $pageIndex;//是否还有下一页
      	    return $page;
      	}


}
